if exists (select 1
          from sysobjects
          where  id = object_id('bd_proc_overTimeResult')
          and type in ('P','PC'))
   drop procedure bd_proc_overTimeResult
go


create procedure bd_proc_overTimeResult (@order_id numeric) as
BEGIN
	DECLARE @user_serial bigint --
	DECLARE @returnRemark varchar(max) = '' --若单子被拒绝，这个是拒绝原因（多人拒绝，这里是全部人的）
	DECLARE @operator bigint --操作人，是加班申请单中的最后审批人
	DECLARE @beginDate DATE
	--获取驳回原因
	select @returnRemark = (SELECT
			'('+remark +')'
		FROM
			bd_kq_approvalRecord
		WHERE
			order_id = @order_id
			AND approve_key ='overtime'
			AND approve_order NOT IN ( 0, 9999 )
			AND status = 0
		FOR XML PATH(''))
	--更新单子的取消/驳回原因
	update bd_over_time_order
		set return_remark = @returnRemark
		where order_id = @order_id

	--处理排班明细数据
	DECLARE @status int --单子状态
	DECLARE @sourceKey int --单子来源
	select @status = status,@sourceKey = source_key from bd_over_time_order where order_id = @order_id;
	--若单子被驳回（@status=2），并且来源是排班加班（@sourceKey=2）,则需要将排班明细表中的is_created_ot = 0
	if @status=2 and @sourceKey=2
		BEGIN
			--将排班明细表中的is_created_ot = 0
			update d
					set is_created_ot = 0
			from bd_kq_schedule_detail d
			INNER JOIN  (select o.ot_date,j.user_serial
				from lr_jiaba j
				INNER JOIN bd_over_time_order o on j.order_id = o.order_id
				where o.order_id = @order_id
			) x on x.user_serial = d.user_serial and x.ot_date = d.shift_date

		END
	--调用考勤重新计算
	DECLARE @users VARCHAR(MAX) = ''
	DECLARE @overTimeDate DATE

	SELECT
		@users = @users + CAST(u.user_serial AS VARCHAR(100)) + ','
	FROM (
			select DISTINCT user_serial from lr_jiaba where order_id = @order_id
	) u

	SET @users = SUBSTRING(@users,0, LEN(@users))
	SELECT @overTimeDate = ot_date from bd_over_time_order where order_id = @order_id
	EXEC bd_proc_timecard @overTimeDate,@users,5


END
go
